﻿using System;
using System.IO;
using Telerik.Windows.Controls;
using TruckScale.Helpers;

namespace TruckScale.ViewModels
{
  public class VersionViewModel : ViewModelBase
  {
    public string Theme { get; set; } = Global._weighConfig["Theme"];
    public string MainFontSize { get; set; } = Global._weighConfig["MainFontSize"];
    
    public VersionResponse VersionInfo { get; set; }
    public DelegateCommand UpdateCommand { get; private set; }
    public VersionViewModel()
    {
      GetVersionInfo();

      UpdateCommand = new DelegateCommand(OnUpdateExecuted, OnCanUpdateExecuted);
    }

    private bool OnCanUpdateExecuted(object obj)
    {
      return true;
    }

    private async void OnUpdateExecuted(object obj)
    {
      try
      {
        // 指定要下载的版本 ID 和本地文件路径
        int versionId = VersionInfo.Id; // 你可以根据实际情况调整
        string localFilePath = Path.Combine(Environment.CurrentDirectory, "Update");
        Directory.CreateDirectory(localFilePath);
        localFilePath = Path.Combine(localFilePath, VersionInfo.Version + ".zip");
        // 使用工具类下载文件
        await HttpClientHelper.DownloadFileAsync(versionId, localFilePath);

        Console.WriteLine("文件下载成功！");
      }
      catch (Exception ex)
      {
        // 处理异常
        Console.WriteLine($"文件下载时出错: {ex.Message}");
      }
    }

    private async void GetVersionInfo()
    {
      try
      {
        // 使用工具类获取版本信息
        VersionInfo = await HttpClientHelper.GetVersionInfo();

        if (VersionInfo != null)
        {
          // 显示版本信息
          //VersionInfo = $"版本号: {versionInfo.Version}\n描述: {versionInfo.Description}\n路径: {versionInfo.Path}";
        }
        else
        {
          //VersionInfo =  "未能获取版本信息";
        }
      }
      catch (Exception ex)
      {
        // 处理异常
        //VersionInfo = $"获取版本信息时出错: {ex.Message}";
      }
    }
  }
}
